package com.molichuxing.gateway.bff.advert.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.gateway.bff.advert.convertor.Convert;
import com.molichuxing.gateway.bff.advert.entity.request.create.AdvertCreateVo;
import com.molichuxing.gateway.bff.advert.entity.request.modify.AdvertModifyVo;
import com.molichuxing.gateway.bff.advert.entity.response.AdvertDealerStoreVo;
import com.molichuxing.gateway.bff.advert.entity.response.AdvertStoreVo;
import com.molichuxing.gateway.bff.advert.entity.response.AdvertVo;
import com.molichuxing.gateway.bff.advert.entity.response.BrandAndDealerVo;
import com.molichuxing.gateway.bff.advert.services.AdvertBffService;
import com.molichuxing.services.business.dto.request.create.AdvertBizCreateDto;
import com.molichuxing.services.business.dto.request.modify.AdvertBizModifyDto;
import com.molichuxing.services.business.dto.response.AdvertBizDto;
import com.molichuxing.services.business.dto.response.DealerStoreInfoBizDto;
import com.molichuxing.services.business.service.AdvertBizService;
import com.molichuxing.services.business.service.StoreBizService;
import com.molichuxing.services.infrastructure.dto.response.DealerDto;
import com.molichuxing.services.infrastructure.dto.response.StoreDto;
import com.molichuxing.services.infrastructure.dto.response.VehicleMakeDto;
import com.molichuxing.services.infrastructure.service.AdvertisingStoreService;
import com.molichuxing.services.infrastructure.service.DealerService;
import com.molichuxing.services.infrastructure.service.StoreService;
import com.molichuxing.services.infrastructure.service.VehicleMakeService;

@Service("AdvertBffService")
public class AdvertBffServiceImpl implements AdvertBffService{

	@Resource
	private AdvertBizService advertBizService;
	
	@Resource
	private DealerService dealerService;
	
	@Resource
	private VehicleMakeService vehicleMakeService;
	
	@Resource
	private StoreBizService storeBizService;
	
	@Resource
	private AdvertisingStoreService advertisingStoreService;
	
	@Resource
	private StoreService storeService;
	
	/**
	 * 获取广告列表
	 * 
	 * @param map
	 *            参数
	 *key:name
	 *            String 广告名称 非必填
	 *key:position
	 *            Integer 广告位置（1:终端屏保广告   2:APP开机广告） 非必填
	 *key:startTime
	 *            String 请求开始时间 非必填
	 *key:endTime
	 *            String 请求结束时间 非必填
	 *key:pageNum
	 *            Integer 当前页
	 *key:pageSize
	 *            Integer 每页显示条数
	 * @return
	 */
	@Override
	public Paged<AdvertVo> getAdvertList(Map<String, Object> map) throws Exception {
		Paged<AdvertBizDto> paged = advertBizService.getAdvertList(map);
		if(null == paged) {
			return new Paged<>();
		}else if(paged.isEmpty()) {
			return new Paged<>(null,paged.getTotal(),paged.getPageSize());
		}
		List<AdvertBizDto> list = paged.getList();
		List<AdvertVo> voList = new ArrayList<>();
		for (AdvertBizDto dto : list) {
			AdvertVo vo = new AdvertVo();
			BeanUtils.copyProperties(dto, vo);
			voList.add(vo);
		}
		Integer pageSize=paged.getPageSize();
		Long total=paged.getTotal();
		Paged<AdvertVo> page=new Paged<>(voList,total,pageSize);
		return page;
	}
	
	/**
	 * 根据id查询广告信息
	 * @param id
	 * @return
	 */
	@Override
	public AdvertVo getAdvertById(Integer id) {
		AdvertBizDto bizDto = advertBizService.getAdvertById(id);
		if(null == bizDto) {
			return null;
		}
		AdvertVo vo = new AdvertVo();
		BeanUtils.copyProperties(bizDto, vo);
		return vo;
	}
	
	/**
	 * 新增广告
	 * @param createVo
	 * @return
	 */
	@Override
	public Boolean create(AdvertCreateVo createVo) {
		Assert.notNull(createVo.getPosition(), "广告位置不能为空");
		Assert.hasLength(createVo.getName(), "广告名称不能为空");
		AdvertBizCreateDto createDto =new AdvertBizCreateDto();
		BeanUtils.copyProperties(createVo, createDto);
		return advertBizService.create(createDto);
	}
	
	/**
	 * 修改广告
	 * @param modifyVo
	 * @return
	 */
	@Override
	public Boolean modify(AdvertModifyVo modifyVo) {
		Assert.notNull(modifyVo.getAdvertId(), "广告id不能为空");
		AdvertBizModifyDto modifyDto =new AdvertBizModifyDto();
		BeanUtils.copyProperties(modifyVo, modifyDto);
		return advertBizService.modify(modifyDto);
	}
	
	
	/**
	 * 获取经销商和品牌接口
	 * 
	 * @param type 1：品牌 2：经销商
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<BrandAndDealerVo> getBrandAndDealerList(Integer type) throws Exception {
		// status 1：营业中
		List<BrandAndDealerVo> voList = new ArrayList<>();
		if(type == null) {
			voList = getVehicleMakeDto(voList);
		}else if (type == 1) {
			voList = getVehicleMakeDto(voList);
		}else {
			voList = getAllDealerList(voList);
		}
		return voList;
	}
	
	
	/**
	 * 获取主品牌信息
	 * @param voList
	 * @return
	 * @throws Exception
	 */
	private List<BrandAndDealerVo> getVehicleMakeDto(List<BrandAndDealerVo> voList) throws Exception{
		//是否是主品牌（ 0:否，1是）
		List<VehicleMakeDto> vehicleList = vehicleMakeService.getVehicleMakeDto(1);
		if(null != vehicleList && !vehicleList.isEmpty()) {
			for (VehicleMakeDto dto : vehicleList) {
				BrandAndDealerVo vo =new BrandAndDealerVo();
				vo.setId(dto.getId());
				vo.setName(dto.getName());
				voList.add(vo);
			}
		}
		return voList;
	}
	
	/**
	 * 获取经销商信息
	 * @param voList
	 * @return
	 * @throws Exception
	 */
	private List<BrandAndDealerVo> getAllDealerList(List<BrandAndDealerVo> voList) throws Exception{
		List<DealerDto> dealerList= dealerService.getAllDealerList(1, null, null);
		if(null != dealerList && !dealerList.isEmpty()) {
			for (DealerDto dto : dealerList) {
				BrandAndDealerVo vo =new BrandAndDealerVo();
				vo.setId(dto.getDealerId());
				vo.setName(dto.getShortName());
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 获取投放门店信息
	 * @param type  1：品牌 2：经销商
	 * @param typeId  品牌id经销商id
	 * @param advertId 广告id
	 * @return
	 * @throws Exception
	 */
	@Override
	public AdvertDealerStoreVo getDealerAndStoreList(Integer type, Integer typeId, Integer advertId) throws Exception {
		//查询门店id
		List<Integer> storeIds = advertisingStoreService.getAdvertisingStoreByAdvertId(advertId);
		
		AdvertDealerStoreVo vo =new AdvertDealerStoreVo();
		//获取已绑定门店
		vo = getSelectedStores(storeIds,vo);
		Map<String, Object> map = new HashMap<>();
		if(null != type && null != typeId) {
			if(type==1) {
				map.put("brandId", typeId);
			}else {
				map.put("dealerId", typeId);
			}
		}
		List<StoreDto> storeList = storeService.getStoreList(map);
		vo = getWaitStores(storeIds,vo,storeList);
		return vo;
	}
	
	/**
	 * 获取已绑定门店
	 * @param storeIds
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	private AdvertDealerStoreVo getWaitStores(List<Integer> storeIds,AdvertDealerStoreVo vo,List<StoreDto> storeList) throws Exception {
		if(null == storeList || storeList.isEmpty()) {
			return vo;
		}
		List<Integer> waitStoreIds =new ArrayList<>(storeList.size());
		for (StoreDto storeDto : storeList) {
			waitStoreIds.add(storeDto.getStoreId());
		}
		//status 营业状态（1：正常，2：暂停营业，3：关店）
		List<DealerStoreInfoBizDto> dealerStores = storeBizService.getDealerStoreInfoBystoreIdList(waitStoreIds,1,storeIds);
		List<AdvertStoreVo> advertStoreVos = Convert.toAdvertStoreVo(dealerStores);
		vo.setWaitStores(advertStoreVos);
		return vo;
	}
	
	/**
	 * 获取已绑定门店
	 * @param storeIds
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	private AdvertDealerStoreVo getSelectedStores(List<Integer> storeIds,AdvertDealerStoreVo vo) throws Exception {
		if(null == storeIds ||storeIds.isEmpty()) {
			return vo;
		}
		//status 营业状态（1：正常，2：暂停营业，3：关店）
		List<DealerStoreInfoBizDto> dealerStores = storeBizService.getDealerStoreInfoBystoreIdList(storeIds,null,null);
		List<AdvertStoreVo> advertStoreVos = Convert.toAdvertStoreVo(dealerStores);
		vo.setSelectedStores(advertStoreVos);
		return vo;
	}
	
	/**
	 * 新增门店与广告的绑定关系
	 * @param storeIds
	 * @param advertId
	 * @return
	 */
	@Override
	public Boolean createAdvertStore(String storeIds, Integer advertId) {
		List<Integer> storeList = null;
		if(StringUtils.isNoneBlank(storeIds)) {
			storeList = new ArrayList<>();
			String[] split = storeIds.split(",");
			for (String storeId : split) {
				storeList.add(Integer.valueOf(storeId));
			}
		}
		return advertBizService.createAdvertStore(storeList, advertId);
	}
}
